//
//  LVCalendarGirdView.m
//  u76ho
//
//  Created by m-air-01 on 16/1/13.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "LVCalendarGirdView.h"
#import "LVCalendarCell.h"
@interface LVCalendarGirdView ()
{
    UIImageView * _imageView;
    UIView * view;
    
    UICollectionView * _collectionView;
    
    
    NSInteger myYear;
    NSInteger myMonth;
    NSInteger myDay;
    
    NSMutableArray * selectedArr;
}
@property (nonatomic , strong) NSArray *weekDayArray;
@property (nonatomic,strong) NSDate * date;
@property (nonatomic,strong) NSDate * today;
@property (nonatomic,strong) UILabel * monthLabel;

@end
static int tempflag = 0;
@implementation LVCalendarGirdView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addScreenShot];
        [self main];
    }
    return self;
}
- (void)setDate:(NSDate *)date
{
    _date = date;
    [_monthLabel setText:[NSString stringWithFormat:@"%.2ld-%li",(long)[self month:_date],(long)[self year:_date]]];
    [selectedArr removeAllObjects];
    for (int i = 0; i<42; i++) {
        [selectedArr addObject:@"0"];
    }
//    NSLog(@"**********%@",selectedArr);
    [_collectionView reloadData];
}

-(void)addScreenShot{
    _imageView = [[UIImageView alloc]initWithFrame:self.bounds];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    _imageView.userInteractionEnabled = YES;
    [_imageView addGestureRecognizer:tap];
    UIImage * image = [UIImage imageScreenView:RootWindow];
    _imageView.image = image.blurImage();
    [self addSubview:_imageView];
}
-(void)main
{
    selectedArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<42; i++) {
        [selectedArr addObject:@"0"];
    }
    CGFloat myW = SCREEN_WIDTH -SIZETO6W(25)*2;
    CGFloat myH = myW + 61 + 90;
    view = [[UIView alloc]initWithFrame:CGRectMake(SIZETO6W(25), SCREEN_HEIGHT/2-myH/2, myW, myH)];
    view.userInteractionEnabled = YES;
    view.backgroundColor = [UIColor whiteColor];
    [self addSubview:view];
    
    [self addSwipe];

    //绿色头标题
    UIView * headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, myW, 61)];
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(30, 61/2-15, 30, 30);
    [leftBtn setImage:[UIImage imageNamed:@"上月"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerV addSubview:leftBtn];
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(headerV.width-30-30, 61/2-15, 30, 30);
    [rightBtn setImage:[UIImage imageNamed:@"下月"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerV addSubview:rightBtn];
    
    _monthLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, headerV.width-100, 61)];
    _monthLabel.textAlignment = NSTextAlignmentCenter;
    _monthLabel.textColor = UIColorFromRGB(0xFFFFFF);
    [headerV addSubview:_monthLabel];
    
    
    headerV.backgroundColor = UIColorFromRGB(0x6ec844);
    [view addSubview:headerV];
    
    //中间的重要部分
    UIView * centerV = [[UIView alloc]initWithFrame:CGRectMake(0, headerV.bottom, myW, myW)];
    [view addSubview:centerV];
    
    //下面的两个按钮
    UIView * bottomV = [[UIView alloc]initWithFrame:CGRectMake(0, centerV.bottom, myW, 90)];
    [view addSubview:bottomV];
    
    NSArray * arr = @[@"取消",@"确认"];
    CGFloat btnW = (myW - SIZETO6W(22) - SIZETO6W(23)*2)/2;
    for (int i = 0; i<2; i++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(SIZETO6W(23)+i*(btnW+SIZETO6W(22)), 45/2, btnW, 45);
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor = [UIColorFromRGB(0x6ec844) CGColor];
        btn.layer.borderWidth = 1.0;
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        btn.layer.cornerRadius = 20;
        btn.tag = i+1;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:UIColorFromRGB(0x6ec844) forState:UIControlStateNormal];
        
        [bottomV addSubview:btn];
        
    }
    
    [self animation:view addSize:YES];

    
    _date = [NSDate date];
    _today = _date;
    
    
    //获得系统日期
    NSCalendar  * cal=[NSCalendar  currentCalendar];
    NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:_today];
    
    myDay = [conponent day];
    myYear = [conponent year];
    myMonth = [conponent month];
    
    
    
    [_monthLabel setText:[NSString stringWithFormat:@"%.2ld-%li",(long)[self month:_date],(long)[self year:_date]]];
    CGFloat littleW = (myW - SIZETO6W(20)*2)/7;
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.itemSize = CGSizeMake(littleW, littleW);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;

    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(SIZETO6W(20), SIZETO6W(20), littleW*7, littleW*7) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    [_collectionView registerClass:[LVCalendarCell class] forCellWithReuseIdentifier:@"LVCalendarCell"];
    _weekDayArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    [centerV addSubview:_collectionView];
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    [self removrFromeSuperViewers];
}
-(void)animation:(UIView *)myView addSize:(BOOL)is
{
    CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = 0.2f;
    animation.repeatCount = 1;
    
    if (is) {
        animation.autoreverses = NO;
        animation.fromValue = [NSNumber numberWithFloat:0.0f];
        animation.toValue = [NSNumber numberWithFloat:1.0f];
        [myView.layer addAnimation:animation forKey:@"alertyes"];
    }else{
        animation.autoreverses = YES;
        animation.fromValue = [NSNumber numberWithFloat:1.0f];
        animation.toValue = [NSNumber numberWithFloat:0.0f];
        [myView.layer addAnimation:animation forKey:@"alertno"];
    }
}
-(void)removrFromeSuperViewers
{
    _imageView.hidden = YES;
    [self animation:self addSize:NO];
    
    [self performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.2];
    
}


#pragma -mark collectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return _weekDayArray.count;
    } else {
        return 42;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //选中的日期
    
    
    LVCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LVCalendarCell" forIndexPath:indexPath];
    cell.dateLabel.backgroundColor = UIColorFromRGB(0xFFFFFF);
    if (indexPath.section == 0) {
        [cell.dateLabel setText:_weekDayArray[indexPath.row]];
        [cell.dateLabel setTextColor:UIColorFromRGB(0x333944)];
    } else {
        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
        
        NSInteger day = 0;
        NSInteger i = indexPath.row;
        
        if (i < firstWeekday) {
            [cell.dateLabel setText:@""];
            
        }else if (i > firstWeekday + daysInThisMonth - 1){
            [cell.dateLabel setText:@""];
        }else{
            day = i - firstWeekday + 1;
            [cell.dateLabel setText:[NSString stringWithFormat:@"%i",(int)day]];
            [cell.dateLabel setTextColor:UIColorFromRGB(0x333944)];
            
            //this month
            if ([_today isEqualToDate:_date] == YES) {
                if (day == [self day:_date]) {
                    [cell.dateLabel setTextColor:UIColorFromRGB(0x333944)];
                    cell.dateLabel.backgroundColor = UIColorFromRGB(0x6ec844);
                    cell.layer.masksToBounds = YES;
                    NSLog(@"有特码相同了**********");
                    tempflag ++;
                    cell.dateLabel.tag = indexPath.row + 1;
                    cell.flag = selectedArr[indexPath.item];
                    cell.layer.cornerRadius = cell.dateLabel.frame.size.width/2;
                } else if (day > [self day:_date]) {
                    [cell.dateLabel setTextColor:UIColorFromRGB(0xC0C5C4)];
                    cell.layer.masksToBounds = YES;
                    cell.layer.cornerRadius = cell.dateLabel.frame.size.width/2;
                }
                else
                {
                    cell.dateLabel.backgroundColor = UIColorFromRGB(0xFFFFFF);
                    cell.dateLabel.tag = indexPath.row + 1;
                    cell.layer.masksToBounds = YES;
                    cell.flag = selectedArr[indexPath.item];
                    cell.layer.cornerRadius = cell.dateLabel.frame.size.width/2;
                }
            } else if ([_today compare:_date] == NSOrderedAscending) {
                [cell.dateLabel setTextColor:UIColorFromRGB(0xC0C5C4)];
//                cell.flag = selectedArr[indexPath.item];
                cell.dateLabel.backgroundColor = UIColorFromRGB(0xFFFFFF);
            }
            else
            {
                cell.dateLabel.backgroundColor = UIColorFromRGB(0xFFFFFF);
                cell.dateLabel.tag = indexPath.row + 1;
                cell.layer.masksToBounds = YES;
                cell.flag = selectedArr[indexPath.item];
                cell.layer.cornerRadius = cell.dateLabel.frame.size.width/2;
                tempflag ++;
            }
        }
    }
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
        
        NSInteger day = 0;
        NSInteger i = indexPath.row;
        
        if (i >= firstWeekday && i <= firstWeekday + daysInThisMonth - 1) {
            day = i - firstWeekday + 1;
            
            //this month
            if ([_today isEqualToDate:_date]) {
                if (day <= [self day:_date]) {
                    return YES;
                }
            } else if ([_today compare:_date] == NSOrderedDescending) {
                return YES;
            }
        }
    }
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.date];
    NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
    
    NSInteger day = 0;
    NSInteger i = indexPath.row;
    day = i - firstWeekday + 1;
    
    myDay = day;
    myYear = [comp year];
    myMonth = [comp month];
    for (int i = 0; i<42; i++) {
        if (i == indexPath.item) {
            [selectedArr replaceObjectAtIndex:indexPath.item withObject:@"1"];
        }
        else
        {
            [selectedArr replaceObjectAtIndex:i withObject:@"0"];
        }
    }
//    NSLog(@"********%@",selectedArr);
    [_collectionView reloadData];
    NSLog(@"点击了");
    
    LVCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LVCalendarCell" forIndexPath:indexPath];
    cell.dateLabel.text = @"哈哈";
    
//    if (self.calendarBlock) {
//        self.calendarBlock(day, [comp month], [comp year]);
//    }
//    
//    [self hide];
}

#pragma mark - btn的点击事件
-(void)leftBtnAction:(UIButton *)btn
{
    
    
    [UIView transitionWithView:view duration:0.5 options:UIViewAnimationOptionTransitionCurlDown animations:^(void) {
        self.date = [self lastMonth:self.date];
    } completion:nil];

}
-(void)rightBtnAction:(UIButton *)btn
{
    [UIView transitionWithView:view duration:0.5 options:UIViewAnimationOptionTransitionCurlUp animations:^(void) {
        self.date = [self nextMonth:self.date];
    } completion:nil];

}
-(void)btnAction:(UIButton *)btn
{
    
    
    if (btn.tag == 1) {
        [self removeFromSuperview];
    }
    else
    {
        if (myMonth) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"caledarNoti" object:@[[NSNumber numberWithInteger:myYear],[NSNumber numberWithInteger:myMonth],[NSNumber numberWithInteger:myDay]]];
            [self removeFromSuperview];
        }
    }
}

#pragma mark - date

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}


- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}

- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}

- (NSInteger)totaldaysInMonth:(NSDate *)date{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}

- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (void)addSwipe
{
    UISwipeGestureRecognizer *swipLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightBtnAction:)];
    swipLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [view addGestureRecognizer:swipLeft];
    
    UISwipeGestureRecognizer *swipRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftBtnAction:)];
    swipRight.direction = UISwipeGestureRecognizerDirectionRight;
    [view addGestureRecognizer:swipRight];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
